<template>
   <el-dialog
      title="查看权限"
      v-model="dialogVisible"
      width="800px"
   >
      <h1>总数：{{ permissionList.length }}</h1>
      <div style="height: 10px"></div>
      <div class="assign-permission-container">
         <div class="permission-tree-container">
            <!-- 左侧菜单部分 -->
            <div class="left-menu">
               <div class="search-box">
                  <el-input
                     placeholder="关键字搜索"
                     v-model="searchText"
                     prefix-icon="Search"
                     clearable
                     @clear="clearSearch"
                  ></el-input>
               </div>

               <div class="menu-tree">
                  <div
                     v-for="group in filteredGroups"
                     :key="group.group_name"
                     class="menu-item"
                     :class="{ active: activeGroupName === group.group_name }"
                     @click="activeGroupName = group.group_name"
                  >
                     <div class="menu-item-header">
                        <span>{{ group.group_name }}</span>
                        <span
                           v-if="getGroupCheckedCount(group.list) > 0"
                           class="checked-count"
                           >({{ getGroupCheckedCount(group.list) }})</span
                        >
                     </div>

                     <div class="sub-menu-list">
                        <div
                           v-for="parentGroup in getParentGroups(group.list)"
                           :key="parentGroup.parent_name"
                           class="sub-menu-item"
                        >
                           <span>{{ parentGroup.parent_name }}</span>
                           <span
                              v-if="getCheckedCount(parentGroup.items) > 0"
                              class="checked-count"
                              >({{ getCheckedCount(parentGroup.items) }})</span
                           >
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            <!-- 右侧详细权限部分 -->
            <div class="right-permission-detail">
               <div class="permission-list">
                  <div
                     v-for="group in searchText ? filteredGroups : permissionGroups"
                     :key="group.group_name"
                     class="permission-section"
                     :id="`group-${group.group_name}`"
                     v-show="activeGroupName === group.group_name || searchText"
                  >
                     <div class="section-header">
                        <span class="section-title">{{ group.group_name }}</span>
                        <el-tag
                           size="small"
                           type="info"
                           class="permission-count"
                        >
                           {{ getGroupCheckedCount(group.list) }}/{{ group.list.length }}
                        </el-tag>
                     </div>

                     <div class="section-content">
                        <el-card
                           v-for="parentGroup in getParentGroups(group.list)"
                           :key="parentGroup.parent_name"
                           class="permission-card"
                           shadow="hover"
                        >
                           <template #header>
                              <div class="permission-group-header">
                                 <span class="parent-title">{{ parentGroup.parent_name }}</span>
                                 <el-tag
                                    size="small"
                                    type="success"
                                    class="permission-count"
                                 >
                                    {{ getCheckedCount(parentGroup.items) }}/{{ parentGroup.items.length }}
                                 </el-tag>
                              </div>
                           </template>

                           <div class="permission-items">
                              <el-tag
                                 v-for="item in parentGroup.items"
                                 :key="item.id"
                                 :type="item.is_checked === 1 ? 'primary' : 'info'"
                                 :effect="item.is_checked === 1 ? 'dark' : 'plain'"
                                 class="permission-tag"
                                 :class="{ 'permission-disabled': item.status !== 1 }"
                              >
                                 <span>{{ item.child_name }}</span>
                              </el-tag>
                           </div>
                        </el-card>
                     </div>
                  </div>
               </div>
               <div
                  v-if="searchText ? filteredGroups.length === 0 : !currentGroup"
                  class="empty-tip"
               >
                  {{ searchText && filteredGroups.length === 0 ? "没有找到匹配的权限" : "请在左侧选择一个权限分组" }}
               </div>
            </div>
         </div>
      </div>
   </el-dialog>
</template>

<script setup>
   import { ref, computed, watch, defineExpose } from "vue";
   import api from "@/api/index.js";
   import { ElMessage } from "element-plus";
   const dialogVisible = ref(false); // 弹窗是否显示
   const permissionList = ref([]); // 权限列表数据

   const openDialog = (data) => {
      // 1. 重置状态
      searchText.value = "";
      activeGroupName.value = "";
      permissionGroups.value = [];
      // 2. 打开弹窗
      dialogVisible.value = true;
      // 3. 拉取数据
      GetPermissions(data);
      getAllPermissions();
   };
   const GetPermissions = async (data) => {
      const res = await api.authority.getUserInfo({ id: data.id });
      if (res.code == 200) {
         permissionList.value = res.data.auth_codes;
      } else {
         ElMessage.error(res.msg);
      }
   };

   // 角色ID
   const roleId = ref(null);

   // 角色数据
   const roleData = ref({});

   // 权限分组数据
   const permissionGroups = ref([]);

   // 搜索
   const searchText = ref("");

   // 当前激活的权限组
   const activeGroupName = ref("");

   // 清除搜索
   const clearSearch = () => {
      searchText.value = "";
   };

   // 当前选中的权限组
   const currentGroup = computed(() => {
      return permissionGroups.value.find((g) => g.group_name === activeGroupName.value) || null;
   });

   // 过滤后的权限分组
   const filteredGroups = computed(() => {
      if (!permissionGroups.value || permissionGroups.value.length === 0) {
         return [];
      }

      if (!searchText.value) {
         return permissionGroups.value;
      }

      // 搜索过滤
      const keyword = searchText.value.toLowerCase();

      // 处理后的结果
      const result = [];

      // 遍历每个权限组
      permissionGroups.value.forEach((group) => {
         // 匹配组名称
         const isGroupMatched = group.group_name.toLowerCase().includes(keyword);

         // 找出所有匹配的子项
         const matchedItems = (group.list || []).filter(
            (item) =>
               item.child_name?.toLowerCase().includes(keyword) ||
               item.parent_name?.toLowerCase().includes(keyword) ||
               (item.route_url && item.route_url.toLowerCase().includes(keyword))
         );

         // 如果组名称匹配或者有匹配的子项
         if (isGroupMatched || matchedItems.length > 0) {
            // 如果组名称匹配，保留整个组
            if (isGroupMatched) {
               result.push({ ...group });
            }
            // 否则创建一个新组，只包含匹配的项和它们的父项
            else {
               // 创建新的组对象
               const newGroup = {
                  ...group,
                  list: [],
               };

               // 提取所有匹配项的父项名称
               const parentNames = [...new Set(matchedItems.map((item) => item.parent_name).filter(Boolean))];

               // 获取所有包含这些父项名称的子项
               newGroup.list = (group.list || []).filter(
                  (item) =>
                     matchedItems.includes(item) || // 原本匹配的子项
                     (item.parent_name && parentNames.includes(item.parent_name)) // 匹配项的同级项（相同父项）
               );

               // 如果有子项，添加到结果中
               if (newGroup.list.length > 0) {
                  result.push(newGroup);
               }
            }
         }
      });

      return result;
   });

   // 已选权限列表
   const selectedPermissions = computed(() => {
      const result = [];
      permissionGroups.value.forEach((group) => {
         if (group.list && Array.isArray(group.list)) {
            group.list.forEach((permission) => {
               if (permission.is_checked === 1) {
                  result.push({
                     ...permission,
                     group_name: group.group_name,
                  });
               }
            });
         }
      });
      return result;
   });

   // 已选权限数量
   const selectedPermissionsCount = computed(() => {
      return selectedPermissions.value.length;
   });

   // 获取所有权限列表
   const getAllPermissions = async () => {
      try {
         const res = await api.authority.getAuthList();

         if (res.code === 200) {
            console.log("API返回的原始权限数据:", res.data);
            console.log("用户权限列表:", permissionList.value);

            // 将API返回的数据转换为所需格式
            const formattedGroups = [];

            // 处理API返回的权限数据
            res.data.forEach((group) => {
               // 检查菜单项是否有效
               if (!group || !group.auth_code) return;

               // 创建权限组
               const formattedGroup = {
                  group_name: group.name || "未命名权限组",
                  auth_code: group.auth_code,
                  list: [],
               };

               // 添加一级菜单自身作为权限项
               formattedGroup.list.push({
                  id: group.id,
                  parent_name: "一级菜单",
                  child_name: group.name,
                  auth_code: group.auth_code,
                  status: group.status || 1,
                  is_checked: Array.isArray(permissionList.value) && permissionList.value.includes(group.auth_code) ? 1 : 0,
                  route_url: group.route_url || "",
                  show_sort: group.show_sort || 0,
               });
               // 处理子权限
               if (group.children && Array.isArray(group.children)) {
                  group.children.forEach((child) => {
                     // 检查子项是否有效
                     if (!child || !child.auth_code) return;

                     // 将子权限添加到列表中
                     formattedGroup.list.push({
                        id: child.id,
                        parent_name: group.name,
                        child_name: child.name,
                        auth_code: child.auth_code,
                        status: child.status || 1,
                        is_checked: Array.isArray(permissionList.value) && permissionList.value.includes(child.auth_code) ? 1 : 0,
                        route_url: child.route_url || "",
                        show_sort: child.show_sort || 0,
                     });

                     // 处理孙级权限
                     if (child.children && Array.isArray(child.children)) {
                        child.children.forEach((grandchild) => {
                           // 检查孙项是否有效
                           if (!grandchild || !grandchild.auth_code) return;

                           formattedGroup.list.push({
                              id: grandchild.id,
                              parent_name: child.name,
                              child_name: grandchild.name,
                              auth_code: grandchild.auth_code,
                              status: grandchild.status || 1,
                              is_checked: Array.isArray(permissionList.value) && permissionList.value.includes(grandchild.auth_code) ? 1 : 0,
                              route_url: grandchild.route_url || "",
                              show_sort: grandchild.show_sort || 0,
                           });
                        });
                     }
                  });
               }

               // 添加到权限组列表
               formattedGroups.push(formattedGroup);
            });

            console.log("处理后的权限组数据:", formattedGroups);

            // 更新权限组数据
            permissionGroups.value = formattedGroups;

            // 如果有权限组，默认选中第一个
            if (formattedGroups.length > 0) {
               activeGroupName.value = formattedGroups[0].group_name;
            }
         } else {
            ElMessage.error(res.msg || "获取权限列表失败");
         }
      } catch (error) {
         console.error("获取权限列表出错:", error);
         ElMessage.error("获取权限列表失败");
      }
   };

   // 按父级菜单分组
   const getParentGroups = (permissions) => {
      if (!permissions || !Array.isArray(permissions)) {
         return [];
      }

      // 按parent_name分组
      const groups = {};
      permissions.forEach((item) => {
         const parentName = item.parent_name || "其他";
         if (!groups[parentName]) {
            groups[parentName] = {
               parent_name: parentName,
               items: [],
               checked: false,
               indeterminate: false,
            };
         }
         groups[parentName].items.push(item);
      });

      // 计算父级菜单的选中状态
      Object.values(groups).forEach((group) => {
         updateParentCheckedState(group);
      });

      // 转换为数组并排序
      return Object.values(groups).sort((a, b) => {
         const itemA = a.items[0];
         const itemB = b.items[0];
         return (itemA?.show_sort || 0) - (itemB?.show_sort || 0);
      });
   };

   // 更新父级菜单的选中状态
   const updateParentCheckedState = (parentGroup) => {
      const allChecked = parentGroup.items.every((item) => item.is_checked === 1);
      const anyChecked = parentGroup.items.some((item) => item.is_checked === 1);

      parentGroup.checked = allChecked;
      parentGroup.indeterminate = anyChecked && !allChecked;
   };

   // 检查分组是否全选
   const isGroupChecked = (items) => {
      if (!items || !Array.isArray(items) || items.length === 0) return false;
      return items.every((item) => item.is_checked === 1);
   };

   // 检查分组是否部分选中
   const isGroupIndeterminate = (items) => {
      if (!items || !Array.isArray(items) || items.length === 0) return false;
      const anyChecked = items.some((item) => item.is_checked === 1);
      const allChecked = items.every((item) => item.is_checked === 1);
      return anyChecked && !allChecked;
   };

   // 获取已选中数量
   const getCheckedCount = (items) => {
      if (!items || !Array.isArray(items)) return 0;
      return items.filter((item) => item.is_checked === 1).length;
   };

   // 获取分组已选中数量
   const getGroupCheckedCount = (items) => {
      if (!items || !Array.isArray(items)) return 0;
      return items.filter((item) => item.is_checked === 1).length;
   };

   // 处理权限组选中状态变化
   const handleGroupCheck = (checked, group) => {
      if (group.list && Array.isArray(group.list)) {
         group.list.forEach((item) => {
            if (item.status === 1) {
               // 只选择启用状态的权限
               item.is_checked = checked ? 1 : 0;
            }
         });
      }

      // 强制刷新已选列表
      forceRefreshSelectedPermissions();
   };

   // 处理父级菜单选中状态变化
   const handleParentCheck = (checked, items) => {
      if (items && Array.isArray(items)) {
         items.forEach((item) => {
            if (item.status === 1) {
               // 只选择启用状态的权限
               item.is_checked = checked ? 1 : 0;
            }
         });
      }

      // 强制刷新已选列表
      forceRefreshSelectedPermissions();
   };

   // 处理权限勾选状态变化
   const handlePermissionCheck = (permission, parentGroup) => {
      // 更新父级菜单的选中状态
      if (parentGroup) {
         updateParentCheckedState(parentGroup);
      }

      // 确保触发计算
      forceRefreshSelectedPermissions();
   };

   // 强制刷新已选列表
   const forceRefreshSelectedPermissions = () => {
      const temp = [...permissionGroups.value];
      permissionGroups.value = temp;
   };

   // 滚动到选择的权限组
   const scrollToGroup = (groupName) => {
      // 给DOM更新一点时间
      setTimeout(() => {
         const element = document.getElementById(`group-${groupName}`);
         if (element) {
            element.scrollIntoView({ behavior: "smooth", block: "start" });
         }
      }, 50);
   };

   // 监听activeGroupName变化，滚动到对应位置
   watch(activeGroupName, (newVal) => {
      if (newVal) {
         scrollToGroup(newVal);
      }
   });

   defineExpose({
      openDialog,
   });
</script>
<style scoped>
   .el-table {
      margin-bottom: 20px;
   }
   .assign-permission-dialog :deep(.el-dialog__body) {
      padding: 10px 20px;
      max-height: 70vh;
      overflow: hidden;
   }

   .assign-permission-container {
      width: 100%;
      height: 60vh;
      display: flex;
      flex-direction: column;
   }

   .permission-tree-container {
      display: flex;
      flex: 1;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      overflow: hidden;
      height: 100%;
   }

   /* 左侧菜单样式 */
   .left-menu {
      width: 260px;
      border-right: 1px solid #e0e0e0;
      background-color: #f5f7fa;
      height: 100%;
   }

   .search-box {
      padding: 10px;
      border-bottom: 1px solid #e0e0e0;
   }

   .menu-tree {
      padding: 10px 0;
      overflow-y: auto;
      height: calc(100% - 64px);
   }

   .menu-item {
      padding: 0 10px;
   }

   .menu-item.active {
      background-color: #f0f2f5;
   }

   .menu-item-header {
      height: 40px;
      line-height: 40px;
      display: flex;
      align-items: center;
      cursor: pointer;
   }

   .menu-item-header .el-checkbox {
      margin-right: 5px;
   }

   .checked-count {
      margin-left: 5px;
      font-size: 12px;
      color: #f56c6c;
   }

   .sub-menu-list {
      padding-left: 20px;
   }

   .sub-menu-item {
      height: 32px;
      line-height: 32px;
      display: flex;
      align-items: center;
   }

   .sub-menu-item .el-checkbox {
      margin-right: 5px;
   }

   /* 右侧详细权限样式 */
   .right-permission-detail {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
      height: 100%;
   }

   .permission-list {
      height: 100%;
   }

   .permission-section {
      margin-bottom: 20px;
      scroll-margin-top: 10px;
   }

   .section-header {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 15px;
      display: flex;
      align-items: center;
   }

   .section-header .el-checkbox {
      margin-right: 10px;
   }

   .section-title {
      flex: 1;
   }

   .section-content {
      padding-left: 20px;
   }

   .permission-card {
      margin-bottom: 15px;
   }

   .permission-group-header {
      display: flex;
      align-items: center;
   }

   .parent-title {
      flex: 1;
      margin-left: 5px;
   }

   .permission-count {
      margin-left: 10px;
   }

   .permission-items {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
   }

   .permission-tag {
      margin-right: 5px;
      margin-bottom: 5px;
      cursor: default;
   }

   .permission-disabled {
      opacity: 0.6;
      text-decoration: line-through;
   }

   .empty-tip {
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #909399;
      font-size: 14px;
   }

   /* 底部按钮样式 */
   .dialog-footer {
      display: flex;
      justify-content: center;
      gap: 20px;
   }

   .dialog-footer .el-button {
      min-width: 100px;
   }
   ::v-deep .el-pagination.is-background .el-pager li.is-active {
      background-color: #000 !important;
   }
   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__inner:hover) {
      border-color: #626aef !important;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      border-color: #6860ff;
   }
   :deep(.el-button:hover) {
      background-color: #e2e4fd;
      color: #6860ff;
   }
   :deep(.el-input__wrapper:hover) {
      box-shadow: inset 0 0 0 1px #6860ff;
   }
</style>
